import { Layout, Image, message, Modal, Button } from 'antd';
import { useState, useEffect, useRef } from 'react';
import { useRouter } from '@/router/hooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import {
  useChatPage,
  useConfig,
  useConfigActions,
  useHotIssueList,
  useInitializeData,
  useAppInfo,
} from '@/store/configStore';
import homeback from '@/assets/images/background/homepagebg.svg';
import MessageSendInputHome from './components/MessageSendInputHome';
import { SvgIcon } from '@/components/icon';
import HeaderLogo from '@/pages/components/logo';
import HomeMenuList from '../components/menus/HomeMenuList';
import './style/homepage.css';
import appService from '@/api/services/appService';

import { UpdateBrandingInfo, hotIssues, imageMap } from '@/common/types';

import FunasrRecorder from '@/pages/chat/components/FunasrRecorder';

import { BrandingEnum } from '@/common';
// import CustomeTitle from '@/pages/components/logo/CustomeTitle';
import CustomeTitle from '@/pages/app-qa/components/header';
// import Header from '@/pages/app-orchestration/components/Header'

import JoyrideGuide from '@/pages/components/joyride-guide';
import { useIsTourStart, useIsTourGuide, useIsFirstLogin, useTourActions } from '@/store/tourStore';

import { RightOutlined } from '@ant-design/icons';

import LicenseModal from '@/pages/components/modal/LicenseConfirm';
import { Header } from 'antd/es/layout/layout';
import Back from '@/components/router/Back';
import { useWorkBench } from '@/store/configStore';

const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;

export default function PermissionPage() {
  const initializeData = useInitializeData();
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);
  const workbench = useWorkBench();

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const { isPc } = useWindowWidth();
  const router = useRouter();
  const { id } = useConfig();
  const chatPage = useChatPage();
  const hotIssueList = useHotIssueList();
  const config = useConfig();
  const { setLinkParams, setConfig } = useConfigActions();

  const [logoShow, setLogoShow] = useState(false);
  const appInfoInitialize = useAppInfo();

  // const { setIsTourStart, setIsTourGuide } = useTourActions();
  const isTourStart = useIsTourStart();
  // const isTourGuide = useIsTourGuide();
  // const isFirstLogin = useIsFirstLogin();

  // useEffect(() => {
  //   isFirstLogin && setIsTourGuide(isFirstLogin);
  // }, [isFirstLogin]);

  const hotImages = [
    { icon: 'hot-book', color: '#CE33E6' },
    { icon: 'hot-case', color: '#6C82FF' },
    { icon: 'hot-fire', color: '#C966FF' },
    { icon: 'hot-note', color: '#946BF1' },
    { icon: 'hot-school', color: '#6B53FF' },
  ];

  const getRandomHotImage = (index: number) => {
    // const randomIndex = Math.floor(Math.random() * hotImages.length);
    const randomIndex = index % hotImages.length;
    return (
      <SvgIcon
        icon={hotImages[randomIndex].icon}
        size={25}
        color={hotImages[randomIndex].color}
        style={{
          padding: '3px',
          marginRight: '6px',
          backgroundColor: '#E5E7ED',
          borderRadius: '8px',
          flexShrink: 0,
        }}
      />
    );
  };

  const [hotTitle, setHotTitle] = useState<hotIssues[]>([]);

  const handleSend = () => { };
  const changeInputType = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    setVoice(!voice);
  };
  const handleInterrupt = () => { };
  const onSTT = (status: number) => {
    if (status == 0) {
      setIsMessageSend(true);
    }
    if (status == 1) {
      setIsMessageSend(true);
    }
    if (status == 2) {
      setIsMessageSend(false);
    }
  };
  const onVoiceStop = (inputValue: string) => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    inputValue &&
      router.pushQuery(chatPage, {
        msg: inputValue,
      });
  };
  const onInterrupt = () => {
    setIsMessageSend(false);
  };
  const [voice, setVoice] = useState(false);

  const [isMessageSend, setIsMessageSend] = useState(false);

  useEffect(() => {
    setLogoShow(isTourStart);
  }, [isTourStart]);

  // useEffect(() => {
  //   if (hotIssueList?.length > 0) {
  //     setHotTitle(hotIssueList);
  //   } else {
  //     if (id) {
  //       appService
  //         .brandingDetail(id, 'app')
  //         .then((res: UpdateBrandingInfo) => {
  //           setHotTitle(res?.hot_issues);
  //         })
  //         .catch((error) => {
  //           console.log(error);
  //         });
  //     } else {
  //       appService.initialize().then((appResponse) => {
  //         const { id, share_id } = appResponse?.app;
  //         if (id && share_id) {
  //           setLinkParams({
  //             id,
  //             share_id,
  //           });
  //           setConfig({ ...config, id, share_id });
  //           appService
  //             .brandingDetail(id, 'app')
  //             .then((res: UpdateBrandingInfo) => {
  //               setHotTitle(res?.hot_issues);
  //             })
  //             .catch((error) => {
  //               console.log(error);
  //             });
  //         }
  //       });
  //     }
  //   }

  //   setTimeout(() => {
  //     !isPc && checkTextOverflow();
  //   }, 500);
  // }, []);

  const checkTextOverflow = () => {
    const scrollTextElements = document.querySelectorAll('.scrolltext');
    console.log(scrollTextElements);

    scrollTextElements.forEach((element) => {
      const spanElement = element.querySelector('span');
      console.log(
        spanElement.offsetWidth,
        element.offsetWidth,
        spanElement.offsetWidth / element.offsetWidth,
      );

      if (spanElement.offsetWidth > element.offsetWidth) {
        const translateXValue = `${(1 - spanElement.offsetWidth / element.offsetWidth) * 100}%`;
        console.log(translateXValue);

        // 如果文本超出容器，则添加动画类
        spanElement.classList.add('animate');
        // spanElement.style.setProperty('--translateXValue', translateXValue);
        spanElement.style.setProperty('--translateXValue', translateXValue);
        // console.log(element.style);
      } else {
        // 如果文本没有超出容器，则移除动画类
        spanElement.classList.remove('animate');
        // spanElement.style.removeProperty('--translateXValue');
      }
    });
  };

  return (
    <>
      <JoyrideGuide />

      <Layout
        className="homepage-layout h-full [-ms-overflow-style:none] [scrollbar-width:none]"
        style={{
          background: 'rgb(236,239,247)',
          // height: '100svh'
          height:
            licenseFlag && !initializeData?.is_license_valid && isPc
              ? 'calc(100svh - 60px)'
              : 'calc(100svh - 10px)',
        }}
      >

        <Header style={{ background: '#FBFCFF', padding: 0, borderBottom: '1px solid #DDE5FF', height: '60px', lineHeight: '60px' }}>
          <div className="flex items-center">
            <div className="flex">
              <Back
                title={'全部应用'}
                onClick={() => {
                  router.push(workbench);
                }}
              />
            </div>
          </div>
        </Header>
        {/* <Header /> */}
        <CustomeTitle />

        <div
          onClick={() => {
            setLogoShow(!logoShow);
          }}
        >
          {/* {!isPc && <HeaderLogo />} */}
        </div>

        <div
          className="mt-24 flex flex-col  items-center self-center"
          style={{
            width: isPc ? '800px' : '80%',
            margin: 'auto',
            paddingBottom: isPc ? '100px' : '50px',
            paddingTop: isPc ? 'unset' : '60px',
          }}
        >
          {
            appInfoInitialize &&
            <div style={{ width: '360px', maxWidth: '100%', height: '200px', padding: '0 5px' }}>
              {appInfoInitialize?.industry_type ? (
                <img src={imageMap[appInfoInitialize?.industry_type]} alt="" />
              ) : (
                <img src={homeback} alt="" />
              )}
            </div>
          }

          {
            appInfoInitialize &&
            <div style={{ fontSize: '14px', color: '#847BBA' }}>
              {appInfoInitialize?.home_text ? appInfoInitialize?.home_text : BrandingEnum.home_text}
            </div>
          }

          <div
            className="jr-step-1 flex items-center border-none py-4"
            style={
              !isPc
                ? {
                  width: '100%',
                }
                : {}
            }
          >
            {/* <div
              style={{
                display: 'flex',
                width: isPc ? '800px' : '100%',
                position: 'relative',
              }}
            >
              <MessageSendInputHome
                handleSend={handleSend}
                changeInputType={changeInputType}
                handleInterrupt={handleInterrupt}
                isMessageSend={isMessageSend}
                isHome={true}
              ></MessageSendInputHome>
            </div> */}

            <div
              style={{
                display: 'flex',
                width: isPc ? '800px' : '100%',
                position: 'relative',
              }}
            >
              {voice == true ? (
                <FunasrRecorder
                  isMessageSend={isMessageSend}
                  onInterrupt={onInterrupt}
                  onStop={onVoiceStop}
                  onSTT={onSTT}
                  onSwitch={changeInputType}
                  className="flex h-full w-full items-center justify-center"
                />
              ) : (
                <MessageSendInputHome
                  handleSend={handleSend}
                  changeInputType={changeInputType}
                  handleInterrupt={handleInterrupt}
                  isMessageSend={isMessageSend}
                  isHome={true}
                ></MessageSendInputHome>
              )}
            </div>
          </div>

          <div
            className="flex flex-wrap justify-center gap-x-6"
            style={{ width: isPc ? '800px' : '100%' }}
          >
            {hotTitle?.slice(0, 5).map((item, index) => {
              return (
                <div
                  className="hot-card"
                  key={index}
                  style={{
                    fontSize: '14px',
                    color: 'black',
                    height: '40px',
                    background: '#F9FBFF',
                    display: 'flex',
                    alignItems: 'center',
                    padding: '0 8px',
                    marginTop: '10px',
                    cursor: 'pointer',
                    width: isPc ? 'unset' : '100%',
                  }}
                  onClick={() => {
                    if (licenseFlag && !initializeData?.is_license_valid) {
                      handleActivateClick();
                      return;
                    }
                    router.pushQuery(chatPage, {
                      msg: item.content,
                    });
                  }}
                >
                  <div>{getRandomHotImage(index)}</div>
                  <div className="scrolltext">
                    <span>{item.content}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* <div>
          {isPc ? (
            <HomeMenuList />
          ) : (
            <div style={{ display: logoShow ? 'block' : 'none' }}>{<HomeMenuList />}</div>
          )}
        </div> */}
      </Layout>
      <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
    </>
  );
}
